package fun.formoji.commons.config;

import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.convert.converter.Converter;

import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <code>DateConvert</code>
 * <desc>
 * 描述：
 * <desc/>
 * <b>Creation Time:</b> 2021/1/31 0:39.
 *
 * @author hshe
 */
@Data
public class DateConvert implements Converter<String, Date> {

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";


    @Override
    public Date convert(@NotNull String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        try {
            source = source.trim();
            if (source.contains(":")) {
                SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
                return formatter.parse(source);
            } else if (source.matches("^\\d+$")) {
                Long time = Long.valueOf(source);
                return new Date(time);
            }
        } catch (ParseException e) {
            throw new IllegalArgumentException("[DateConverter] convert date parseException ", e);
        }
        throw new IllegalArgumentException("[DateConverter] not match timestamp or date ");
    }
}
